#include <QCoreApplication>
#include <QtCore>
#include <Ice/Ice.h>
#include <thread>
#include <QSettings>
#include "robotscripti.h"


class Server : public Ice::Application
{
public:
    Server(QCoreApplication* p){
        m_pApp = p;
    }
    virtual int run(int argc, char* argv[]){
        // Init
        QString strRootDir = QCoreApplication::applicationDirPath();
        QDir::setCurrent(strRootDir);

        QSettings *pSettingCore = new QSettings("./Config/Robot.ini", QSettings::IniFormat);
        pSettingCore->setIniCodec("UTF-8");
        strScriptDir = pSettingCore->value("File/ScriptsDir").toString();
        QDir *pDir = new QDir(strScriptDir);
        if(!pDir->exists()){
            pDir->mkpath(strScriptDir);
        }

        // Ice object
        Ice::ObjectAdapterPtr adapter = communicator()->createObjectAdapter("Robot");

        // Script
        RobotScriptI* pScriptI = new RobotScriptI();
        adapter->add(pScriptI, communicator()->stringToIdentity("Script"));


        adapter->activate();

        communicator()->waitForShutdown();

        g_pRobotScript->SetExit();

        QCoreApplication::processEvents();
//        m_pApp->quit();
        m_pApp->exit();
        return 0;
    }
private:
    QCoreApplication* m_pApp;

};

void t_run(QCoreApplication* p){
    Server app(p);
    app.main(__argc, __argv);
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    std::thread t1(t_run, &a);
    t1.detach();
    return a.exec();
}
